package org.jeecg.modules.engineer.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.custom.entity.MtCustomEquip;
import org.jeecg.modules.engineer.entity.MtEngineer;
import org.jeecg.modules.engineer.service.IMtEngineerService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.order.entity.MtRepairDispatch;
import org.jeecg.modules.order.entity.MtRepairDispose;
import org.jeecg.modules.order.entity.MtRepairOrder;
import org.jeecg.modules.order.service.IMtRepairDispatchService;
import org.jeecg.modules.order.service.IMtRepairDisposeService;
import org.jeecg.modules.order.service.IMtRepairOrderService;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 工程师表
 * @Author: jeecg-boot
 * @Date: 2022-08-16
 * @Version: V1.0
 */
@Api(tags = "工程师表")
@RestController
@RequestMapping("/engineer/mtEngineer")
@Slf4j
public class MtEngineerController extends JeecgController<MtEngineer, IMtEngineerService> {
    @Autowired
    private IMtEngineerService mtEngineerService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMtServiceProvidersService mtServiceProvidersService;
    @Autowired
    private IMtServiceStationService mtServiceStationService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMtRepairOrderService mtRepairOrderService;
    @Autowired
    private IMtRepairDisposeService mtRepairDisposeService;
    @Autowired
    private IMtRepairDispatchService mtRepairDispatchService;

    /**
     * 分页列表查询
     *
     * @param mtEngineer
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工程师表-分页列表查询")
    @ApiOperation(value = "工程师表-分页列表查询", notes = "工程师表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "engineer/MtEngineerList")
    public Result<IPage<MtEngineer>> queryPageList(MtEngineer mtEngineer,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<MtEngineer> queryWrapper = QueryGenerator.initQueryWrapper(mtEngineer, req.getParameterMap());
        Page<MtEngineer> page = new Page<MtEngineer>(pageNo, pageSize);
        IPage<MtEngineer> pageList = mtEngineerService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据登录用户查询工程师列表
     *
     * @param mtEngineer
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "工程师表-根据登录用户查询工程师列表", notes = "工程师表-根据登录用户查询工程师列表")
    @GetMapping(value = "/stationEngineerList")
    public Result<IPage<MtEngineer>> stationEngineerList(MtEngineer mtEngineer,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<MtEngineer> queryWrapper = QueryGenerator.initQueryWrapper(mtEngineer, req.getParameterMap());
        Page<MtEngineer> page = new Page<MtEngineer>(pageNo, pageSize);
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为服务商,根据账号获取服务商下属工程师
        if (sysUser.getUserType() == 1) {
            MtServiceProviders providers = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(providers)) {
                return Result.error("无该服务商信息");
            }
            queryWrapper.lambda().eq(MtEngineer::getProviderId, providers.getId()).orderByAsc(MtEngineer::getStationId);
        }
        // 用户为工作站或工程师时,根据账号获取工作站下属工程师
        else if (sysUser.getUserType() == 2) {
            MtServiceStation station = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(station)) {
                return Result.error("无该工作站信息");
            }
            queryWrapper.lambda().eq(MtEngineer::getStationId, station.getId());
        }
        // 其他
        else {
            IPage<MtEngineer> pageList = mtEngineerService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        IPage<MtEngineer> pageList = mtEngineerService.page(page, queryWrapper);
        // 获取工程师下属未完成工单
        for (MtEngineer engineer : pageList.getRecords()) {
            engineer.setOrderNum(mtRepairOrderService.getProcessingListByEngineer(engineer.getId()).size());
        }
        return Result.OK(pageList);
    }

    /**
     * 根据当前登录的账号 获取服务商信息或服务站信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "根据当前登录的账号 获取服务商信息或服务站信息", notes = "根据当前登录的账号 获取服务商信息或服务站信息")
    @PutMapping(value = "/getInfoByLoginUser")
    public Result getInfoByLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        // 角色为服务商
        if (loginUser.getUserType() == 1) {
            MtServiceProviders mtServiceProviders = mtServiceProvidersService.getById(loginUser.getLinkId());
            return Result.OK(mtServiceProviders);
        }
        // 角色为服务站
        else if (loginUser.getUserType() == 2) {
            MtServiceStation mtServiceStation = mtServiceStationService.getById(loginUser.getLinkId());
            return Result.OK(mtServiceStation);
        }
        return Result.ok();
    }


    /**
     * 获取当前登录工程师信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取当前登录工程师信息", notes = "获取当前登录工程师信息")
    @GetMapping(value = "/getEngineerInfoByLoginUser")
    public Result getEngineerInfoByLoginUser() {
        //获取当前账号
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为工程师
        if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, loginUser.getUsername()));
            return Result.ok(loginEngineer);
        }
        // 其他
        else {
            return Result.ok();
        }
    }

    /**
     * 添加
     *
     * @param mtEngineer
     * @return
     */
    @AutoLog(value = "工程师表-添加")
    @ApiOperation(value = "工程师表-添加", notes = "工程师表-添加")
    @RequiresPermissions("engineer:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MtEngineer mtEngineer) {
        //mtEngineerService.save(mtEngineer);
        mtEngineerService.saveEngineerAndCreateUser(mtEngineer);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mtEngineer
     * @return
     */
    @AutoLog(value = "工程师表-编辑")
    @ApiOperation(value = "工程师表-编辑", notes = "工程师表-编辑")
    @RequiresPermissions("engineer:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtEngineer mtEngineer) {
        mtEngineerService.updateById(mtEngineer);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工程师表-通过id删除")
    @ApiOperation(value = "工程师表-通过id删除", notes = "工程师表-通过id删除")
    @RequiresPermissions("engineer:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mtEngineerService.removeEngineerAndUserRole(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工程师表-批量删除")
    @ApiOperation(value = "工程师表-批量删除", notes = "工程师表-批量删除")
    @RequiresPermissions("engineer:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //this.mtEngineerService.removeByIds(Arrays.asList(ids.split(",")));
        mtEngineerService.removeEngineersAndUserRolesByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工程师表-通过id查询")
    @ApiOperation(value = "工程师表-通过id查询", notes = "工程师表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MtEngineer> queryById(@RequestParam(name = "id", required = true) String id) {
        MtEngineer mtEngineer = mtEngineerService.getById(id);
        if (mtEngineer == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mtEngineer);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mtEngineer
     */
    @RequiresPermissions("engineer:export")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtEngineer mtEngineer) {
        return super.exportXls(request, mtEngineer, MtEngineer.class, "工程师表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("engineer:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MtEngineer.class);
    }

}
